package com.xidian.zhiancloud.controller.ledgerManagerment.targetAndSystem;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SecurityCulturalActivityLedger;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.qo.ledgerManagerment.targetAndSystem.SecurityCulturalActivityLedgerQO;
import com.xidian.zhiancloud.service.ledgerManager.targerAndSystem.SecurityCulturalActivityLedgerService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityCulturalActivityLedgerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 台账管理 目标职责与制度 安全文化活动台账
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:29
 */
@RestController
@RequestMapping("/SecurityCulturalActivityLedger")
public class SecurityCulturalActivityLedgerController extends BaseController {
    @Autowired
    private SecurityCulturalActivityLedgerService securityCulturalActivityLedgerService;

    @Autowired
    private OrganizationService organizationService;
    /**
     * 增加安全文化活动台账对象
     *
     * @param securityCulturalActivityLedger 安全文化活动台账对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SecurityCulturalActivityLedger securityCulturalActivityLedger) {
        securityCulturalActivityLedger.setCompanyId(getSessionUserCompanyId());
        securityCulturalActivityLedger.setCreatorId(getSessionUserid());
        securityCulturalActivityLedger.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = securityCulturalActivityLedgerService.save(securityCulturalActivityLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id查询安全文化活动台账对象
     *
     * @param id 安全文化活动台账对象的id
     * @return 安全文化活动台账对象
     */
    @GetMapping("/getById")
    public ResultDTO<SecurityCulturalActivityLedgerVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(securityCulturalActivityLedgerService.getVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除安全文化活动台账对象
     *
     * @param ids 安全文化活动台账对象的id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = securityCulturalActivityLedgerService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改安全文化活动台账对象
     *
     * @param securityCulturalActivityLedger 安全文化活动台账对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(SecurityCulturalActivityLedger securityCulturalActivityLedger) {
        securityCulturalActivityLedger.setCompanyId(null);
        securityCulturalActivityLedger.setCreatorId(null);
        securityCulturalActivityLedger.setCreateTime(null);
        Boolean res = securityCulturalActivityLedgerService.updateById(securityCulturalActivityLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param securityCulturalActivityLedgerQO 查询参数
     * @return 安全文化活动列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<SecurityCulturalActivityLedgerVO>> getListByQO(SecurityCulturalActivityLedgerQO securityCulturalActivityLedgerQO) {
        if (securityCulturalActivityLedgerQO.getCurrent() == null || securityCulturalActivityLedgerQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        securityCulturalActivityLedgerQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(securityCulturalActivityLedgerService.getListByQO(securityCulturalActivityLedgerQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全文化活动台账导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<SecurityCulturalActivityLedger> list = securityCulturalActivityLedgerService.listByIds(Arrays.asList(ids));
        List<SecurityCulturalActivityLedgerVO> ans = new LinkedList<>();
        list.forEach(t -> {
            SecurityCulturalActivityLedgerVO vo = new SecurityCulturalActivityLedgerVO();
            BeanUtils.copyProperties(t, vo);
            List<Organization> organizations = organizationService.listByIds(Arrays.stream(vo.getParticipateOrganizationIds().split(",")).collect(Collectors.toList()));
            List<String> names = organizations.stream().map(Organization::getName).collect(Collectors.toList());
            vo.setParticipateOrganizationNames(StringUtils.concatStrings(names));
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), SecurityCulturalActivityLedgerVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<SecurityCulturalActivityLedgerVO> list = EasyExcel.read(file.getInputStream()).head(SecurityCulturalActivityLedgerVO.class).sheet().doReadSync();
        List<SecurityCulturalActivityLedger> ans = new LinkedList<>();
        list.forEach(vo -> {
            SecurityCulturalActivityLedger ledger = new SecurityCulturalActivityLedger();
            BeanUtils.copyProperties(vo, ledger);
            ledger.setCreatorId(getSessionUserid());
            ledger.setCompanyId(getSessionUserCompanyId());
            ledger.setCreateTime(new Date(System.currentTimeMillis()));
            String[] names = vo.getParticipateOrganizationNames().split(",");
            List<Long> ids = new LinkedList<>();
            for (String name : names) {
                LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
                organizationLambdaQueryWrapper.eq(Organization::getName,name);
                Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
                if(organization!=null){
                    ids.add(organization.getId());
                }
            }
            ledger.setParticipateOrganizationIds(StringUtils.concatLongs(ids));
            ans.add(ledger);
        });
        Boolean res = securityCulturalActivityLedgerService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
